﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Renren.Controls;
using Renren.ServiceProviders;
using Renren.Services;
using Renren.ViewModels.Page;

namespace Renren.Pages
{
    public partial class MainPage : PhoneApplicationPage
    {
        private bool firstLoaded = true;
        private bool Debug = true;

        public MainPageViewModel ViewModel { get; set; }

        public MainPage()
        {
            InitializeComponent();

            this.ViewModel = new MainPageViewModel();
            FeedService.GetFeed(this.ViewModel.NewsList, RequestType.GetInit);
            DataContext = this.ViewModel;

            this.Loaded += (sender, args) =>
                {
                    if (this.firstLoaded)
                    {
                        Service.VerifyTokenFailed += (s, e) =>
                            {
                                this.NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.Relative));
                            };

                        this.NewsStreamBox.LoadHead += (s, e) => FeedService.GetFeed(this.ViewModel.NewsList, RequestType.GetInit, e.Callback);
                        this.NewsStreamBox.LoadTail += (s, e) => FeedService.GetFeed(this.ViewModel.NewsList, RequestType.GetMore, e.Callback);

                        this.FriendStreamBox.FriendTap += (s, e) =>
                            {
                                PhoneApplicationService.Current.State["UserPage"] = e.Friend.Id;
                                NavigationService.Navigate(new Uri("/UserPage.xaml", UriKind.Relative));
                            };

                        this.firstLoaded = false;
                    }
                };

            ServiceProvider.ResponseError += (sender, args) =>
                {
                    if (Debug)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            System.Windows.MessageBox.Show(args.ErrorCode + "\n" + args.ErrorMessage, "error", MessageBoxButton.OK);
                        });
                    }
                };
        }

        private void RefreshButton_Clicked(object sender, EventArgs e)
        {
            this.NewsStreamBox.Refresh();
            this.FriendStreamBox.StreamBox.Refresh();
        }

        private void SearchButton_Clicked(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/PlacePickerPage.xaml", UriKind.Relative));
        }

        private void StatusButton_Clicked(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/StatusPage.xaml", UriKind.Relative));
        }

        private void Logout_Clicked(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.Relative));
        }

        private void ToggleDebugMode(object sender, EventArgs e)
        {
            Debug = !Debug;
        }

        private void ToggleCache(object sender, EventArgs e)
        {
            RenrenSettings.CacheEnabled = !RenrenSettings.CacheEnabled;
        }

        private void MessageBox_GotFocus(object sender, RoutedEventArgs e)
        {
            NewsBox.ReactEvent = false;
            (sender as Renren.Controls.MessageBox).Text = "";
            for (int i = 0; i < this.NewsStreamBox.Items.Count; i++)
            {
                var item = this.NewsStreamBox.ItemContainerGenerator.ContainerFromIndex(i);
                if (item != null)
                {
                    (item as ListBoxItem).Opacity = 0.4;
                }
            }

            this.ApplicationBar.Opacity = 1;
            this.ApplicationBar.IsVisible = false;
        }

        private void MessageBox_LostFocus(object sender, RoutedEventArgs e)
        {
            NewsBox.ReactEvent = true;
            for (int i = 0; i < this.NewsStreamBox.Items.Count; i++)
            {
                var item = this.NewsStreamBox.ItemContainerGenerator.ContainerFromIndex(i);
                if (item != null)
                {
                    (item as ListBoxItem).Opacity = 1;
                }
            }

            this.ApplicationBar.Opacity = 0.5;
            int count = 0;
            var timer = new DispatcherTimer();
            timer.Tick += (timerSender, timerArgs) =>
            {
                if (count > 3)
                {
                    this.ApplicationBar.IsVisible = true;
                    timer.Stop();
                }
                count++;
            };
            timer.Interval = new TimeSpan(1000 * 1000);
            timer.Start();
        }

        private void MessageBox_Send(object sender, Common.MessageEventArgs e)
        {
            StatusService.PublishStatusOld(e.Message);
            this.Focus();
        }
    }
}